package com.ijtunes.sources;

import com.ijtunes.utils.Logger;
import com.ijtunes.utils.Properties;
import com.ijtunes.utils.Property;
import com.ijtunes.filetypes.Track;
import com.ijtunes.filetypes.ITunesTrack;
import com.ijtunes.iTunesCOM;
import com.itunes.IITFileOrCDTrack;
import com.itunes.IITTrackCollection;
import com.itunes.IITURLTrack;
import com4j.Com4jObject;
import java.util.logging.Level;

/**
 * Builds a collection of tracks based on iTunes
 * @author Michael Sena
 */
public class ITunesSource extends TrackSource {

    private IITTrackCollection trackCollection = null;
    private int localUpTo = 1;
    
    /*
     * Standard constructor.
     */
    public ITunesSource() {
        trackCollection = iTunesCOM.getInstance().libraryPlaylist().tracks();
        count = trackCollection.count();
    }

    @Override
    public final int size() {
        return count;
    }

    @Override
    public final ITunesTrack getNext() {
        ITunesTrack track = null;
        upTo++;
        while (track == null && localUpTo <= count) {
            Com4jObject tempTrack = iTunesCOM.getInstance()
                    .libraryPlaylist().tracks().item(localUpTo);
            if (tempTrack.is(IITFileOrCDTrack.class)) {
                track = new ITunesTrack(
                        tempTrack.queryInterface(IITFileOrCDTrack.class));
                if (!track.exists()) {
                    if (Properties.getBool(Property.DELETE_MISSING)) {
                        track.delete();
                        count--;
                    }
                } else {
                    add((Track) track);
                }
                localUpTo++;
            } else if (tempTrack.is(IITURLTrack.class)) {
                IITURLTrack urlTrack = tempTrack
                        .queryInterface(IITURLTrack.class);
                Logger.log(this, "Skipping URL-based track: " + urlTrack.name(),
                        Level.INFO);
                localUpTo++;
                upTo++;
            } else {
                Logger.log(this, "Track is not a file or URL track.");
            }
        }
        return track;
    }
}
